package cn.whb.hrm.service.impl;

import cn.whb.hrm.constant.TenantTypeConstant;
import cn.whb.hrm.domain.Employee;
import cn.whb.hrm.domain.LoginUser;
import cn.whb.hrm.domain.Tenant;
import cn.whb.hrm.dto.RegisterDto;
import cn.whb.hrm.feign.ILoginUserFeignClient;
import cn.whb.hrm.mapper.EmployeeMapper;
import cn.whb.hrm.mapper.TenantMapper;
import cn.whb.hrm.query.TenantQuery;
import cn.whb.hrm.service.ITenantService;
import cn.whb.hrm.util.AjaxResult;
import cn.whb.hrm.util.encrypt.ValidUtils;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whb
 * @since 2021-12-15
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private ILoginUserFeignClient client;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Page<Tenant> loadTenantType(Page<Tenant> page, TenantQuery query) {
        List<Tenant> tenantList = tenantMapper.loadTenantType(page,query);
        page.setRecords(tenantList);
        return page;
    }


    @Override
    public AjaxResult entering(RegisterDto dto) {

        //利用断言工具进行非空校验
        ValidUtils.assertNotNull(dto,"入住参数为空，请重新输入" );

        Employee employee = dto.getEmployee();
        //利用断言工具进行非空校验
        ValidUtils.assertNotNull(employee,"入住公司管理员为空，请重新输入" );

        Long mealId = dto.getMealId();
        LoginUser loginUser = new LoginUser();
        loginUser.setMealId(mealId);
        loginUser.setPassword(employee.getPassword());
        employee.setType(TenantTypeConstant.ADMIN_EMP);
        loginUser.setType(employee.getType());
        loginUser.setUsername(employee.getUsername());
        AjaxResult result = client.entering(loginUser);
        if (result.isSuccess()){
            Integer loginUserId = (Integer)result.getResultObj();
            employee.setLoginId(Long.valueOf(loginUserId));
            employee.setInputTime(new Date());
            employeeMapper.insert(employee);
            Tenant tenant = dto.getTenant();
            tenant.setAdminId(employee.getId());
            tenant.setRegisterTime(new Date());
            tenantMapper.insert(tenant);
        }
        return result;
    }
}
